package function

object Test01 {
  def main(args: Array[String]): Unit = {
    val fun = (name: String) => {
      println(name)
    }
    fun("匿名函数")

    //匿名函数作为参数传入到另外一个函数
    def f(func: String => Unit): Unit = {
      func("函数作为参数")
    }

    f(fun)
    println("===========================")
    f(println)

    //定义二元运算函数，具体运算方法通过参数传入
    def dualFun(fun: (Int, Int) => Int): Int = {
      fun(1, 2)
    }

    val add = (a: Int, b: Int) => a + b
    val minus = (a: Int, b: Int) => a - b
    println(dualFun(add))
    println(dualFun(minus))
    //还可省略参数类型
    println(dualFun((a, b) => a + b))
    println(dualFun(-_ - _))
    //函数作为一个值进行传递
    val f1: Int => Int = -_
    println(f1(2))

    //函数作为函数返回值返回
    def f5(): Int => Unit = {
      def f6(a: Int): Unit = {
        println("f6调用：" + a)
      }

      f6
    }

    println(f5)


    //对数组进行处理，将操作抽象出来，处理完成后返回一个新的结果
    var arr: Array[Int] = Array(12, 13, 34, 24)

    def arrayOperation(array: Array[Int], op: Int => Int): Array[Int] = {
      for (elem <- array) yield op(elem)
    }

    //定义函数加一
    def addOne(elem: Int): Int = {
      elem + 1
    }

    //调用函数
    val newArray: Array[Int] = arrayOperation(arr, addOne(_))
    println(newArray.mkString(","))
    //传入匿名函数，实现元素翻倍
    val newArray2 = arrayOperation(arr, _ * 2)
    println(newArray2.mkString(","))

    //练习
    val fun1 = (i: Int, s: String, c: Char) => {
      if (i == 0 && s == "" && c == '0') false else true
    }
    println(fun1(0, "", '0'))
    println(fun1(10, "2", '0'))

    //练习
    def func2(i: Int): String => (Char => Boolean) = {
      def f1(s: String): Char => Boolean = {
        def f2(c: Char): Boolean = {
          if (i == 0 && s == "" && c == '0') false else true
        }

        f2
      }

      f1

    }

    println(func2(0)("")('0'))
      //定义成匿名函数简写
      def func4(i: Int): String => (Char => Boolean) = {
        s =>c =>  if (i == 0 && s == "" && c == '0') false else true
      }
    println(func4(0)("")('0'))
    //柯里化
    def func3(i:Int)(s:String)(c:Char):Boolean={
      if(i==0&&s==""&&c=='0') false else true
    }
    println(func3(0)("")('0'))



  }
}
